package tenant

import (
	"context"
	pb "git.mycaigou.com/gfyx/micro-gfyx-user-service/proto/micro_gfyx_user_service_proto/micro-gfyx-user-service/tenant"
	"git.mycaigou.com/gfyx/micro-gfyx-user-service/service/tenant/tenant"
	"git.mycaigou.com/gfyx/micro-gfyx-user-service/service/user"
	"git.myscrm.cn/golang/stark/v4"
)

type tenantServer struct {
	userInfoService user.UserInfoServiceIface
	tenantService   tenant.TenantServiceIface
}

func NewTenantServer(
	userInfoService user.UserInfoServiceIface,
	tenantService tenant.TenantServiceIface,
) pb.TenantServiceServer {
	return &tenantServer{
		userInfoService: userInfoService,
		tenantService:   tenantService,
	}
}

// GetTenantCodeByName 根据租户名称获取租户code
func (s *tenantServer) GetTenantCodeByName(ctx context.Context, request *pb.GetTenantCodeByNameRequest) (*pb.GetTenantCodeByNameResponse, error) {
	var resp = &pb.GetTenantCodeByNameResponse{}

	stark.Logger.Infof(ctx, "grpc GetTenantCodeByName request:%+v", request)

	tenantCode, err := s.userInfoService.GetTenantCodeByName(ctx, request.CompanyName)
	if err != nil {
		stark.Logger.Errorf(ctx, "grpc GetTenantCodeByName request:%+v, err:%s", request, err.Error())
		return nil, err
	}

	resp.TenantCode = tenantCode
	stark.Logger.Infof(ctx, "grpc GetTenantCodeByName request:%+v, response:%+v", request, resp)
	return resp, nil
}

// GetTenantList 获取租户列表
func (s *tenantServer) GetTenantList(ctx context.Context, request *pb.GetTenantListRequest) (*pb.GetTenantListResponse, error) {
	resp, err := s.tenantService.GetTenantList(ctx, request)
	if err != nil {
		stark.Logger.Errorf(ctx, "grpc GetTenantList request:%+v, err:%s", request, err.Error())
		return nil, err
	}
	return resp, nil
}

// GetTenantByName 根据租户名称获取租户信息
func (s *tenantServer) GetTenantByName(ctx context.Context, request *pb.GetTenantByNameRequest) (*pb.GetTenantByNameResponse, error) {
	resp, err := s.tenantService.GetTenantByName(ctx, request)
	if err != nil {
		stark.Logger.Errorf(ctx, "grpc GetTenantByName request:%+v, err:%s", request, err.Error())
		return nil, err
	}
	return resp, nil
}

// GetTenantByCode 根据租户code获取租户信息
func (s *tenantServer) GetTenantByCode(ctx context.Context, request *pb.GetTenantByCodeRequest) (*pb.GetTenantByCodeResponse, error) {
	resp, err := s.tenantService.GetTenantByCode(ctx, request)
	if err != nil {
		stark.Logger.Errorf(ctx, "grpc GetTenantByCode request:%+v, err:%s", request, err.Error())
		return nil, err
	}
	return resp, nil
}

// GetAllEfficientTenant 获取所有有效租户
func (s *tenantServer) GetAllEfficientTenant(ctx context.Context, request *pb.GetAllEfficientTenantRequest) (*pb.GetAllEfficientTenantResponse, error) {
	resp, err := s.tenantService.GetAllEfficientTenant(ctx, request)
	if err != nil {
		stark.Logger.Errorf(ctx, "grpc GetAllEfficientTenant request:%+v, err:%s", request, err.Error())
		return nil, err
	}
	return resp, nil
}
